<template>
  <div class="goods-list">
    <MyHeader title="商品列表页"></MyHeader>
    <MyTable :list="list">
      <template v-slot:header>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>

      <!-- #body="scope" -->
      <template v-slot:body="{ row }">
        <td>{{ row.id }}</td>
        <td>{{ row.goods_name }}</td>
        <td>￥{{ row.goods_price }}</td>
        <td>
          <input
            v-model="row.inputValue"
            @keydown.enter="enterFn(row)"
            @keydown.esc="row.inputValue = ''"
            @blur="row.inputVisible = false"
            v-focus
            class="tag-input form-control"
            style="width: 100px"
            type="text"
            v-if="row.inputVisible"
          />
          <button
            v-else
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
            @click="row.inputVisible = true"
          >
            +Tag
          </button>
          <br />
          <span
            v-for="(item, index) in row.tags"
            :key="index"
            class="badge bg-warning text-dark"
          >
            {{ item }}
          </span>
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="del(row.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyHeader from "../components/MyHeader.vue";
import MyTable from "../components/MyTable.vue";
import axios from "axios";
axios.defaults.baseURL = "https://www.escook.cn";
// 目标: 循环商品列表表格
// 1. 封装MyTable.vue 整体表格组件-一套标签和样式
// 2. axios请求数据
// 3. 传入MyTable组件里循环tr显示数据

// 目标: 展示tags标签
// 1. tags数组 - 某个td循环span使用文字
// 2. span设置bs的样式

// 目标: 删除数据
// 1. 删除按钮 - 点击事件
// 2. 作用域插槽把索引值关联出来了
// scope身上就有row和index
// 3. 删除中使用scope.index的索引值
// 4. 删除事件里删除数组里对应索引值的数据
export default {
  components: {
    MyHeader,
    MyTable,
  },
  data() {
    return {
      list: [],
    };
  },
  created() {
    axios({
      url: "/api/goods",
    }).then((res) => {
      console.log(res);
      this.list = res.data.data;
    });
  },
  methods: {
    del(id) {
      let index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    enterFn(row) {
      if (row.inputValue.trim().length === 0) return alert("!!!!");
      row.tags.push(row.inputValue);
      row.inputValue = "";
    },
  },
};
</script>

<style lang="less" scoped>
.goods-list {
  padding-top: 45px;
}
</style>